import request from '../utils/request';
import TileLayer from 'ol/layer/Tile';
import WMTS from 'ol/source/WMTS';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import { get as getProjection } from 'ol/proj';
import { register } from 'ol/proj/proj4';
import proj4 from 'proj4';

class EgisService {
    constructor() {
        this.clientId = "22a42f65c8c44724b5703efd54bf5782";
        this.clientSecret = "aa9001532bd34279a97e3b01bf6173f9";
        this.token = null;
        //正式域名地址，基础服务
        this.baseUrl = 'https://bncs.mem.gov.cn/egis';
        //认证服务
        this.authUrl = 'https://bncs.mem.gov.cn/egis';
        this.wmtsUrl = 'https://bncs.mem.gov.cn/egis/service/api/egis/base/v1/wmts';
        this.basicAuth = 'Basic ' + btoa(`${this.clientId}:${this.clientSecret}`);
        this.initProjection();
    }

    initProjection() {
        // 定义 EPSG:4490 (CGCS2000)
        proj4.defs('EPSG:4490', '+proj=longlat +ellps=GRS80 +no_defs +type=crs');
        register(proj4);
    }

    async initialize() {
        await this.getToken();
        return this.createWMTSLayers();
    }

    async getToken() {
        try {
            const response = await request({
                url: `${this.authUrl}/oauth/token`,
                method: 'get',
                headers: {
                    'Authorization': this.basicAuth
                }
            });
            this.token = response.access_token;
            return this.token;
        } catch (error) {
            console.error('获取EGIS token失败:', error);
            throw error;
        }
    }

    createWMTSSource(layer) {
        const projection = getProjection('EPSG:4490');
        const projectionExtent = [-180, -90, 180, 90];
        const resolutions = [];
        const matrixIds = [];
        const maxZoom = 20;

        for (let i = 0; i <= maxZoom; i++) {
            resolutions[i] = 360 / (Math.pow(2, i) * 256);
            matrixIds[i] = i.toString();
        }

        const params = {
            layer: layer,
            tilematrixset: 'c',
            Service: 'WMTS',
            Request: 'GetTile',
            Version: '1.0.0',
            Format: 'tiles'
        };

        return new WMTS({
            url: this.wmtsUrl,
            layer: layer,
            matrixSet: 'c',
            format: 'tiles',
            projection: projection,
            tileGrid: new WMTSTileGrid({
                origin: [-180, 90],
                resolutions: resolutions,
                matrixIds: matrixIds,
                tileSize: [256, 256]
            }),
            wrapX: true,
            crossOrigin: 'anonymous',
            tileLoadFunction: (imageTile, src) => {
                const xhr = new XMLHttpRequest();
                const tileCoord = imageTile.getTileCoord();
                const z = tileCoord[0];
                const x = tileCoord[1];
                const y = tileCoord[2];
                const tileParams = {
                    ...params,
                    TileMatrix: z,
                    TileCol: x,
                    TileRow: y
                };
                // console.log('WMTS请求参数:', layer, tileParams);
                const url = `${this.wmtsUrl}?` + new URLSearchParams(tileParams);

                xhr.open('GET', url);
                xhr.setRequestHeader('Authorization', this.basicAuth);
                xhr.responseType = 'arraybuffer';
                
                xhr.onload = () => {
                    if (xhr.status === 200) {
                        const arrayBufferView = new Uint8Array(xhr.response);
                        const blob = new Blob([arrayBufferView], { type: 'tiles' });
                        const urlCreator = window.URL || window.webkitURL;
                        const imageUrl = urlCreator.createObjectURL(blob);
                        imageTile.getImage().src = imageUrl;
                    } else {
                        console.error('加载瓦片失败:', url, xhr.status);
                    }
                };
                
                xhr.onerror = () => {
                    console.error('加载瓦片失败:', url);
                };
                
                xhr.send();
            }
        });
    }

    createWMTSLayers() {
        // 创建矢量底图层
        const cvaLayer = new TileLayer({
            source: this.createWMTSSource('vec'),
            zIndex: 0,
            visible: true,
            opacity: 1
        });

        // 创建注记图层
        const ciaLayer = new TileLayer({
            source: this.createWMTSSource('cva'),
            zIndex: 1,
            visible: true,
            opacity: 1
        });

        return [cvaLayer, ciaLayer];
    }
}

export default EgisService;